package com.test.coder;

import com.test.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;


public class Decoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        Message message = new Message();
        short head = in.readUnsignedByte();
        message.setHead(head);

        byte funCode = in.readByte();
        message.setFunCode(funCode);

        short length = in.readShort();
        message.setMessageLength(length);

        if (length > 0) {
            byte[] bytes = new byte[length];
            in.readBytes(bytes, 0, length);
            message.setMessageData(bytes);
        }

        short crc = in.readShort();
        message.setCrc(crc);

        out.add(message);
    }

}
